package exercises.stack;

import java.util.Stack;

/**
 * @Title:
 * @Description:
 * @Author Fay Wang
 * @Date 2022/4/27 10:50
 * @Version 1.0
 */
public class Q34_IsValid {
    public boolean isValid(String s) {
        if (s == null || s.isEmpty()) {
            return false;
        }
        char[] array = s.toCharArray();
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = array[i];
            if (c == '[' || c == '{' || c == '(') {
                stack.push(c);
            }else {
                if (stack.isEmpty()) {
                    return false;
                }
                char topChar = stack.pop();
                if (c == ')' && topChar != '(') {
                    return false;
                }
                if (c == ']' && topChar != '[') {
                    return false;
                }
                if (c == '}' && topChar != '{') {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

    public boolean isValid1(String s) {
        if (s == null || s.isEmpty()) {
            return false;
        }
        char[] array = s.toCharArray();
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = array[i];
            if (c == '(' ) {
                stack.push(')');
            }else if (c == '[' ) {
                stack.push(']');
            }else if (c == '{' ) {
                stack.push('}');
            } else {
                return !stack.isEmpty() && stack.pop() == c;
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        Q34_IsValid q = new Q34_IsValid();
        String s = "()[]{}";
        String s1 = "([)]";

        System.out.println("s: " + q.isValid(s));
        System.out.println("s1: " + q.isValid(s1));


        System.out.println("s: " + q.isValid1(s));
        System.out.println("s1: " + q.isValid1(s1));
    }
}
